//
//  MyVoiceView.swift
//  imprint
//
//  Created by 小柠檬🍋 on 2025/1/16.
//

import SwiftUI

//制作中的音色
struct CrowdView: View {
    //用于父试图来管理数据
    @ObservedObject var viewModel : MakeVoiceViewModel
    @StateObject private var paymentManager = PaymentManager()
    @State private var showPicker = false //选择图片选择框
    @State var maxItems = 1
    @State private var voiceMedia: MediaItem? = nil //制作的音频文件
    @State private var voiceName : String? = nil //音色音色
    @State var showChoosePrice = false
    @State var fullPayment = false

    var body: some View {
        if !viewModel.status.isEmpty {
            HomeEmptyView(text1: viewModel.status)
        } else {
            VStack {
                ScrollView {
                    // 数据列表
                    ForEach(viewModel.items) { item in
                        CrowdVoiceItemView(item: item)
                    }
                    
                    LoadMoreFooter(refreshing: $viewModel.footerRefreshing, action: {
                        viewModel.getData(false, status: 0)
                    }) {
                        LoadMoreView(noMore: viewModel.noMore, footerRefreshing: viewModel.footerRefreshing)
                    }
                    .noMore(viewModel.noMore)
                    .preload(offset: 10)
                }
                .enableRefresh()
                .onAppear {
                    if !viewModel.isInit {
                        viewModel.getData(true,status: 0)
                        viewModel.isInit = true
                    }
                }
                if !isExamine() {
                    Button(action: {
                        let freeCount = userManager.getUser()?.extraConfig?.aiVoiceCreate ?? 0
                        let endStr = if ((freeCount) > 0) {
                            "\n您当前可免费制作\(freeCount)次"
                        } else {
                            ""
                        }
                        let price = Double(configManager.getConfig().aiChat.aiVoiceClonePrice ?? "0") ?? 0.0
                        let priceStr = "\(price)元"
                        showBtnDialog(text: "因每个人需要的音色需求都不一样，所以这边采用了多人制作模式；\n" +
                                       "1、需要的多人共同制作，当进度达到100%即可制作，参与者都可以使用该音色（满足条件后可全额退款）；\n" +
                                       "2、您当前是发起者，发起者需要提供音频文件10s以上，不要有杂音，背景音乐等，要使用纯语音；\n" +
                                       "3、发起后会在上面列表进行展示，发起之前最好看下上面是否已经有人发起过了，避免重复；\n" +
                                       "4、发起者最低10元，总费用需要\(priceStr)；\n" +
                                       "5、发起之前最好私下组织，也可以在官方群组织，避免没人参与问题；\n" +
                                       "6、音色制作更多是一种精确的模仿过程，而非能够实现百分百的完全还原；\n" +
                                       "7、制作完成后，当购买人数超过30个后，参与制作的人可以全额退款\n" +
                                       "8、请认真考虑后再做决定。" + endStr, alignment: .leading) {
                            if !userManager.isLogin() {
                                showLoginPopup()
                                return
                            }
                            showEditDialog(title: "添加音色名称",hint: "请输入音色名称", content: "") { it in
                                if !(it ?? "").isEmpty {
                                    voiceName = it
                                    showPicker = true
                                }
                            }
                        }
                    }) {
                        Text("发起制作")
                            .foregroundColor(themeManager.themeColor)
                            .font(.system(size: 16))
                            .padding(.horizontal,10)
                            .padding(.vertical,15)
                            .frame(width: 300)
                        
                    }.background(themeManager.themeColor.opacity(0.1))
                        .cornerRadius(8)
                }
            }.sheet(isPresented: $showPicker) {
                MediaPicker(
                    selectionLimit: $maxItems,
                    maxFileSizeMB: 800, // 100MB
                    filterType: MediaFilterType.videos,
                    isPresented: $showPicker,
                    onComplete: { items in
                        showPicker = false
                        voiceMedia = items.first
                        if userManager.getExtraConfig().aiVoiceCreate ?? 0 > 0 {
                            let fullPrice = Double(configManager.getConfig().aiChat.aiVoiceClonePrice ?? "0") ?? 0.0
                            viewModel.doCreate(media: voiceMedia, name: voiceName, price: fullPrice, deduct: true)
                        } else {
                            showChoosePrice = true
                        }
                    }
                )
            }
            .alert("温馨提示", isPresented: $showChoosePrice){
                Button("取消",role: .cancel){}
                Button("10元",role: .destructive){
                    fullPayment = false
                    doCreate()
                }
                Button("全款",role: .destructive) {
                    fullPayment = true
                    doCreate()
                }
            } message: {
                Text("请选择支付方式")
            }
        }
    }
    
    func doCreate(){
        let productID = fullPayment ? "com.aiyu.imprint.voice.create" : "com.aiyu.imprint.voice.create.10"
        let fullPrice = Double(configManager.getConfig().aiChat.aiVoiceClonePrice ?? "0") ?? 0.0
        let price = fullPayment ? fullPrice : 10
        showLoadPopup()
        paymentManager.purchaseProduct(withIdentifier: productID) { result in
            // 处理回调结果
            switch result {
            case .purchasing:
                showToast("正在购买...")
            case .purchased:
                showToast("购买成功")
                viewModel.doCreate(media: voiceMedia, name: voiceName, price: price)
            case .failed(_):
                hideLoadPopup()
                showToast("购买失败")
            case .restored(let productID):
                showToast("恢复购买成功，产品 ID: \(productID)")
            case .deferred:
                showToast("购买延迟处理")
            case .invalidProductID:
                hideLoadPopup()
                showToast("未找到有效的产品 ID")
            case .unknown:
                showToast("未知交易状态")
            }
        }
    }
}

#Preview {
    CrowdView(viewModel:MakeVoiceViewModel())
}
